using System;
using System.Diagnostics;
using Navigant.Infrastructure.Cases;

namespace Navigant.Infrastructure.Helpers
{
	/// <summary>
	/// Logs messages to the Windows Application Event Log.
	/// </summary>
	public static class Logger
	{
        public const string SourceName = "Preservation Noticing Accelerator";

        public static void LogMessage(string message)
        {
            Logger.LogMessage(message, null);
        }

        public static void LogMessage(string message, ICase caseSite)
        {
            Logger.WriteEntry(message, caseSite, EventLogEntryType.Information);
        }

        public static void LogWarning(string message)
        {
            Logger.LogWarning(message, null);
        }

        public static void LogWarning(string message, ICase caseSite)
        {
            Logger.WriteEntry(message, caseSite, EventLogEntryType.Warning);
        }

        public static void LogError(Exception e)
        {
            Logger.LogError(e, null);
        }

        public static void LogError(Exception e, ICase caseSite)
        {
            Logger.WriteEntry(e.ToString(), caseSite, EventLogEntryType.Error);
        }

        private static string AppendCaseSiteMessage(string message, ICase caseSite)
        {
            if (caseSite != null && caseSite.SiteAddress != null)
            {
                return string.Format("{0} \r\n Case Site:  {1}",
                    message, caseSite.SiteAddress.AbsoluteUri);
            }
            else
            {
                return string.Format("{0} \r\n No case site was specified.", message);
            }
        }

        private static void WriteEntry(string message, ICase caseSite, 
            EventLogEntryType entryType)
        {
            try
            {
                EventLog.WriteEntry(Logger.SourceName,
                    Logger.AppendCaseSiteMessage(message, caseSite),
                    entryType);
            }
            // This is the point of no return, cannot do anything with the 
            // exception at this point
            catch { }
        }
	}
}
